﻿using System;
using System.Linq;
using System.Xml.Linq;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using PageTypeBuilder;
using TemplateFoundation.Core;
using TemplateFoundation.CustomProperties;
using TemplateFoundation.Feeds;
using TemplateFoundation.PageTypeIcons;
using TemplateFoundation.Tabs;
using TemplateFoundation.Tags;

namespace TemplateFoundation.PageTypes
{
    /// <summary>
    /// Base class for RSS pages
    /// </summary>
    [PageTypeIcon("~/TemplateFoundation/Images/PageIcons/rss.png")]
    public class ArticleRssPageBase : RssPageBase
    {
        /// <summary>
        /// Gets or sets the tags used to filter this feed
        /// </summary>
        [PageTypeProperty(
            EditCaption = "Tags filter",
            HelpText = "Use this property to limit the feed to articles matching the specified tags",
            UniqueValuePerLanguage = true,
            SortOrder = 100,
            Type = typeof (PropertyTags),
            Tab = typeof (RelatedTab))]
        public override TagCollection Tags { get; set; }

        /// <summary>
        /// Returns the articles to include in the RSS feed
        /// </summary>
        /// <returns></returns>
        public override PageDataCollection GetPages()
        {
            if (!Tags.Any())
            {
                return PageReference.IsNullOrEmpty(PageContact)
                           ? PageFactory.Instance.GetArticles()
                           : PageFactory.Instance.GetArticlesByAuthor(PageContact);
            }

            // Filter by tags
            return PageReference.IsNullOrEmpty(PageContact)
                           ? PageFactory.Instance.GetArticlesByTag(Tags)
                           : PageFactory.Instance.GetArticlesByTagAndAuthor(Tags, PageContact);
        }
    }
}